﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FantasyBlog.DAL;

namespace FantasyBlog.BLL
{
    public static class OpenQueryExtension
    {
        public static IEnumerable<Comment> ApprovedComments(this Post post)
        {
            var comments = (from c in post.Comments
                            where c.comment_approved == "1"
                            orderby c.date
                            select c);
            return comments;
        }

        public static IEnumerable<Comment> ApprovedSonsComments(this Comment comment)
        {
            var comments = (from c in comment.Sons
                            where c.comment_approved == "1"
                            select c);
            return comments;
        }

        public static IQueryable<Post> FilterOpenedPosts(this IQueryable<Post> posts)
        {
            var post = (from p in posts
                        where p.status == "open"
                        orderby p.date descending
                        select p);
            return post;
        }

        public static IQueryable<Comment> FilterOpenedComments(this IQueryable<Comment> comments)
        {
            var comment = (from c in comments
                           where c.comment_approved == "1"
                           select c);
            return comment;
        }

        public static IQueryable<Comment> TakeSkip(this IQueryable<Comment> comments,int page,int take)
        {
            return comments.Skip((page - 1) * take).Take(take);
        }

        public static IQueryable<Post> TakeSkip(this IQueryable<Post> posts, int page, int take)
        {
            return posts.Skip((page - 1) * take).Take(take);
        }

        public static Post Next(this Post p)
        {
            int? nextId =null;
            try
            {
                nextId = (from p2 in Model.PostSet
                               where p2.ID > p.ID && p2.status == "open"
                               select p2.ID).Min();

            }
            catch (System.Exception ex)
            {
                return null;
            }
            if (!nextId.HasValue)
                return null;
            return Model.PostSet.Find(nextId.Value);
        }

        public static Post Preview(this Post p)
        {
            int? nextId = null;
            try
            {
                nextId = (from p2 in Model.PostSet
                          where p2.ID < p.ID && p2.status == "open"
                          select p2.ID).Max();

            }
            catch (System.Exception ex)
            {
                return null;
            }
            if (!nextId.HasValue)
                return null;
            return Model.PostSet.Find(nextId.Value);
        }

        private static BlogModelContainer Model = new BlogModelContainer();
    }
}
